package cn.geminis.warehouse.service.purchase.controller;

import cn.geminis.warehouse.service.inventory.service.InventoryService;
import cn.geminis.warehouse.service.purchase.entity.PurchaseContainer;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

public class PurchaseContainerController {

    private final InventoryService inventoryService;

    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public void save(@RequestBody PurchaseContainer object) {
        if (!ObjectUtils.isEmpty(object.getId())) {
            var old = this.repository.findById(object.getId()).get();
            inventoryService.containerProductBatchChange(old.getProductBatch(), old.getContainer(), old.getAmount() * -1);
        }
        this.repository.save(object);
        inventoryService.containerProductBatchChange(object.getProductBatch(), object.getContainer(), object.getAmount());
    }

    @DeleteMapping
    @Transactional(rollbackFor = Exception.class)
    public void delete(@RequestBody List<String> ids) {
        ids.forEach(id -> {
            var object = this.repository.findById(id).get();
            inventoryService.containerProductBatchChange(object.getProductBatch(), object.getContainer(), object.getAmount() * -1);
            this.repository.delete(object);
        });
    }

}
